//
//  ZPRegisterInformationViewController.m
//  ZPIOSEducation
//
//  Created by mini1 on 2016/12/27.
//  Copyright © 2016年 mini1. All rights reserved.
//

#import "ZPRegisterInformationViewController.h"
#import "ZPSelectCityVC.h"
#import "ZPSelectGradeVC.h"
#import "ZPRegisterLoginViewController.h"

#define zHeaderActionSheetTag    1000


@interface ZPRegisterInformationViewController () <UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITextFieldDelegate>
{
    NSInteger            selectCityId;  // 选中城市的ID
    NSInteger            selectGradeId; // 选中年级的ID
}

@property (weak, nonatomic) IBOutlet UIButton    *userIconBtn;
@property (weak, nonatomic) IBOutlet UIImageView *userIconImg;
@property (weak, nonatomic) IBOutlet UITextField *userName;
@property (weak, nonatomic) IBOutlet UITextField *userIdentityId;
@property (weak, nonatomic) IBOutlet UILabel     *selectCity;
@property (weak, nonatomic) IBOutlet UILabel     *selectGrade;
@property (weak, nonatomic) IBOutlet UIButton    *saveBtn;
@end

@implementation ZPRegisterInformationViewController


- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"新建学生信息";
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"zhenpin_back"] style:UIBarButtonItemStylePlain target:self action:@selector(navLeftButtonClick)];
    
    ViewRadius(self.userIconImg, self.userIconImg.xj_width / 2);
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
    [self.view addGestureRecognizer:tap];

    self.userIconImg.image = nil;

    [self addGestureRecognizer];
}



- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO];
    [self.tabBarController.tabBar setHidden:YES];

}


- (void)navLeftButtonClick
{
    if(_isFirstCreat){
        [self alertController];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
    
}


- (void)alertController
{
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"学生信息为必填信息,请完善" preferredStyle:UIAlertControllerStyleAlert];
    
    // 添加按钮
    __weak typeof(alert) weakAlert = alert;
    [alert addAction:[UIAlertAction actionWithTitle:@"退出登录" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
        [self dismissViewControllerAnimated:YES completion:^{ }];
        
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"继续完善" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    }]];
    [self presentViewController:alert animated:YES completion:nil];
}


- (void)addGestureRecognizer
{
    UITapGestureRecognizer *selectCityTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectCityClick:)];
    [self.selectCity addGestureRecognizer:selectCityTap];
    
    UITapGestureRecognizer *selectGradeTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(selectGradeClick:)];
    [self.selectGrade addGestureRecognizer:selectGradeTap];
}



- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldDidChange) name:UITextFieldTextDidChangeNotification object:nil];
}



#pragma mark - <键盘隐藏>
- (void)dismissKeyboard
{
    [self.userName resignFirstResponder];
    [self.userIdentityId resignFirstResponder];
}




#pragma mark - <选择城市>
- (void)selectCityClick:(UIGestureRecognizer *)reg
{
    ZPSelectCityVC *selectVc = [[ZPSelectCityVC alloc] init];
    // block传值
    __weak typeof(self)weakself = self;
    selectVc.valueBlock1 = ^(NSString *string,NSInteger ID){
        weakself.selectCity.text = string; // block回传城市名
        selectCityId = ID; // block回传 城市ID
        [self textFieldDidChange]; // 文本编辑已经改变
    };
    [self.navigationController pushViewController:selectVc animated:YES];
}



#pragma mark - <选择年级>
- (void)selectGradeClick:(UIGestureRecognizer *)reg
{
    ZPSelectGradeVC *gradeVC = [[ZPSelectGradeVC alloc] init];
//    gradeVC.view.frame = self.view.bounds;
//    [self.view addSubview:gradeVC.view];
    
    __weak typeof(self)weakself = self;
    gradeVC.valueBlock1 = ^(NSString *string,NSInteger ID){
        weakself.selectGrade.text = string;
        selectGradeId = ID;
        [self textFieldDidChange]; // 文本编辑已经改变
    };

    [self presentViewController:gradeVC animated:YES completion:nil];

}



#pragma mark - <上传头像>
- (IBAction)uploadIconClick:(id)sender
{
    [self selectPhoto];
}



- (void)selectPhoto {
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"编辑头像" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles: @"拍照",@"从手机相册选择",nil];
    actionSheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
    actionSheet.tag = zHeaderActionSheetTag;
    [actionSheet showInView:self.view];
    
}


- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex
{
    if (actionSheet.tag == zHeaderActionSheetTag)
    {
        if (buttonIndex == 0)
        {
            [self openCamera];
        }
        else if (buttonIndex == 1)
        {
            [self openpicLibrary];
        }
    }
}


// 访问相机
- (void)openCamera
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        UIImagePickerController * picker = [[UIImagePickerController alloc]init];
        picker.delegate = self;
        picker.allowsEditing = YES;
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:picker animated:YES completion:nil];
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"你没有摄像头" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    }
}


// 访问相册
- (void)openpicLibrary
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
    {
        UIImagePickerController * picker = [[UIImagePickerController alloc]init];
        picker.delegate = self;
        picker.allowsEditing = YES;
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:picker animated:YES completion:nil];
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Error" message:@"你没有摄像头" delegate:nil cancelButtonTitle:@"Drat!" otherButtonTitles:nil];
        [alert show];
    }
}


// 选择完图片或者拍照完成后按确定按钮回调方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)image editingInfo:(NSDictionary<NSString *,id> *)editingInfo
{
    [self dismissViewControllerAnimated:YES completion:nil];
}


// 选择完图片代理回调
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    // 获取照片选择器编辑的图片
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    //压缩图片然后再上传(1.0代表无损 0~~1.0区间)
    NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
    self.userIconImg.image = [UIImage imageWithData:imageData];
    [self.userIconBtn setTitleColor:[UIColor clearColor] forState:UIControlStateNormal];
    [self dismissViewControllerAnimated:YES completion:nil];
}


// 取消选择调用方法
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)textFieldDidChange
{
    if (self.userName.text.length != 0 &&  ![self.selectCity.text  isEqualToString:@"请选择城市"] && ![self.selectGrade.text isEqualToString:@"请选择年级"]) {
        self.saveBtn.enabled = YES;
        [self.saveBtn setBackgroundColor:zMainColor];
    } else {
        self.saveBtn.enabled = NO;
        [self.saveBtn setBackgroundColor:zFreeColor(238, 238, 238, 1)];
    }
}


#pragma mark - <保存新建学生信息>
- (IBAction)saveBtnClick:(id)sender
{
    NSString *userName = self.userName.text;
    NSInteger nameLenght = self.userName.text.length;
    NSString *userIdentity = self.userIdentityId.text;
    NSInteger identityLenght = self.userIdentityId.text.length;
    
    if (userName == nil || userName == NULL || [[userName stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] == 0) {
        [ZPPromptView showMessage:@"输入姓名不能为空"];
        return;
    }
    if (nameLenght < 2 || nameLenght > 10) {
        [ZPPromptView showMessage:@"输入姓名限2-10个字符"];
        return;
    }
    if (![userName zp_isValidName]) {
        [ZPPromptView showMessage:@"输入姓名格式错误"];
        return;
    }
    
    if (identityLenght == 0) {
        
    }else {
        if (![userIdentity zp_isValidIdentity]) {
            [ZPPromptView showMessage:@"身份证号格式错误"];
            return;
        }
    }
    
    if (self.userIconImg.image) {
        [self  upLoadLocalImage];
    }else {
        [self  saveStuInfoWithImgUrl:@""];
    }
    
}

- (void)upLoadLocalImage
{
    [self  showHudithString:@"发送中..."];
    
    AFHTTPSessionManager  *manger = [AFHTTPSessionManager  manager];
    [manger  POST:APIUC@"image/addImage.json" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData  appendPartWithFileData:UIImageJPEGRepresentation(self.userIconImg.image, 1.) name:@"images" fileName: [NSString stringWithFormat:@"%u.jpeg",arc4random()] mimeType:@"image/jpeg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"=======%@",responseObject);
        if ([[responseObject  objectForKey:@"code"] integerValue] == 200) {
            NSArray  *resultArr = [[responseObject  objectForKey:@"result"] objectForKey:@"result"];
            if ([resultArr isKindOfClass:[NSArray  class]] && resultArr.count > 0) {
                [self  saveStuInfoWithImgUrl:[NSString  stringWithFormat:@"%@",[[resultArr  objectAtIndex:0] objectForKey:@"value"]]];
            }else {
                [self  hiddenHud];
                [ZPPromptView  showMessage:@"发送失败"];
            }
            
        }else {
            [self  hiddenHud];
            [ZPPromptView  showMessage:[responseObject  objectForKey:@"codeMsg"]];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self  hiddenHud];
    }];
    
}

- (void)saveStuInfoWithImgUrl:(NSString  *)imgUrl
{
    NSString *memberId = [[ZPAuthStore  sharedZPAuthStore].userToDic  objectForKey:@"memberId"];

    if(_isFirstCreat){
        memberId = [self.userDic  objectForKey:@"memberid"];
    }
    NSMutableDictionary  *paramDic = [NSMutableDictionary  dictionaryWithObjectsAndKeys:
                                      memberId,@"memberId",
                                      self.userName.text,@"stuName",
                                      [NSString stringWithFormat:@"%ld",selectCityId],@"city",
                                      [NSString stringWithFormat:@"%ld",selectGradeId],@"grade",
                                      nil];
    if (self.userIdentityId.text.length > 0) {
        [paramDic  setObject:self.userIdentityId.text forKey:@"idCard"];
    }
    if (imgUrl.length > 0) {
        [paramDic  setObject:imgUrl forKey:@"headUrl"];
    }
    
    [self  showHudithString:@"发送中..."];
    [[ZPNetworking  sharedZPNetworking] POST:APIUC@"user/saveStudent.json" parameters:paramDic progress:^(NSProgress * _Nullable progress) {
        
    } success:^(id  _Nonnull responseObject) {
        NSLog(@"======%@",responseObject);
        [self  hiddenHud];
        
        if ([[responseObject  objectForKey:@"code"] integerValue] == 200) {
            [[NSNotificationCenter  defaultCenter] postNotificationName:@"refreshStudentList" object:nil];
            if(_isFirstCreat){
                 [[ZPAuthStore sharedZPAuthStore] dicToUserEntity:self.userDic];
                NSMutableDictionary *tempDic = [NSMutableDictionary changeType:[responseObject objectForKey:@"result"]];
                
                NSString *homePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/UserInfo.plist"];
                NSMutableDictionary *dataDic = [[NSDictionary dictionaryWithContentsOfFile:homePath] mutableCopy];
                [dataDic  setObject:[NSString  stringWithFormat:@"%@",[tempDic  objectForKey:@"grade"]] forKey:@"grade"];
                [dataDic  setObject:[NSString  stringWithFormat:@"%@",[tempDic  objectForKey:@"headUrl"]] forKey:@"headUrl"];
                [dataDic  setObject:[NSString  stringWithFormat:@"%@",[tempDic  objectForKey:@"name"]] forKey:@"stuName"];
                [dataDic  setObject:[NSString  stringWithFormat:@"%@",[tempDic  objectForKey:@"stuId"]] forKey:@"stuId"];
                [dataDic  setObject:[NSString  stringWithFormat:@"%@",[tempDic  objectForKey:@"stuNumber"]] forKey:@"stuNum"];
                [dataDic  writeToFile:homePath atomically:YES];
                
                [[ZPAuthStore sharedZPAuthStore] resetUserInfoDictionary];
                [[ZPAuthStore sharedZPAuthStore] setWebViewCookiesWithType:1];
                [zUserDefaults setObject:[NSString stringWithFormat:@"%@",[self.userDic objectForKey:@"userName"]] forKey:LastLogInfomation];
                 [self dismissViewControllerAnimated:YES completion:^{
                     
                 }];
            }else{
                [ZPPromptView showMessage:@"创建成功"];
                if ([[self.navigationController.viewControllers firstObject] isKindOfClass:[ZPRegisterLoginViewController class]]) {
                    [self dismissViewControllerAnimated:YES completion:^{
                        
                    }];
                }else{
                    [self.navigationController  popViewControllerAnimated:YES];

                }
            }
            
        }else {
            [ZPPromptView  showMessage:[responseObject  objectForKey:@"codeMsg"]];
        }
        
    } failure:^(NSError * _Nonnull error) {
        [self  hiddenHud];
        
    }];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
